package org.learn.langchain.langchain4jlearn.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author hzy
 * @Description:
 */
@Configuration
public class Utf8EncodingConfig implements WebMvcConfigurer {

    // 配置全局字符编码过滤器
    @Bean
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding(StandardCharsets.UTF_8.name());
        filter.setForceEncoding(true); // 强制覆盖请求和响应的编码
        return filter;
    }

    // 配置String消息转换器为UTF-8
    @Bean
    public StringHttpMessageConverter stringHttpMessageConverter() {
        return new StringHttpMessageConverter(StandardCharsets.UTF_8);
    }

    // 确保所有消息转换器使用UTF-8
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 优先使用UTF-8编码的String转换器
        converters.add(0, stringHttpMessageConverter());

        // 配置Jackson JSON转换器使用UTF-8
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        jsonConverter.setDefaultCharset(StandardCharsets.UTF_8);
        converters.add(jsonConverter);
    }
}

